package com.dokimet.basedialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

/**
 * User: fish
 * E-mail: 709913163@qq.com
 * Date: 2022/12/7
 * Time: 15:34
 * describe: DialogFragment基类
 */
public abstract class BaseDialog extends DialogFragment {

    protected FragmentActivity mActivity;

    protected View rootView;

    private OnBaseDialogDismissListener onBaseDialogDismiss;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (FragmentActivity) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mActivity == null) {
            mActivity = getActivity();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(getLayoutId(), container, false);
        initView(rootView);
        return rootView;
    }

    public static <T extends BaseDialog> T showDialog(FragmentActivity activity, Class<T> dialogClass) {
        return showDialog(activity, dialogClass, null);
    }

    public static <T extends BaseDialog> T showDialog(FragmentActivity activity, Class<T> dialogClass, Bundle args) {
        if(activity==null){
            return null;
        }
        T dialogFragment = null;
        try {
            dialogFragment = dialogClass.newInstance();
            if (args != null) {
                dialogFragment.setArguments(args);
            }
            dialogFragment.mActivity = activity;
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            transaction.add(dialogFragment, dialogClass.getName());
            transaction.commitAllowingStateLoss();
        } catch (IllegalAccessException | java.lang.InstantiationException e) {
            e.printStackTrace();
        }
        return dialogFragment;
    }

    public final <E extends View> E findViewById(int id) {
        try {
            return rootView.findViewById(id);
        } catch (ClassCastException ex) {
            throw ex;
        }
    }

    public boolean isShowing() {
        if (getDialog() == null) {
            return false;
        } else {
            return getDialog().isShowing();
        }
    }


    /**
     * @return Gravity.BOTTOM
     */
    public abstract int getGravity();

    /**
     * 获取布局资源文件
     *
     * @return 布局资源文件id值
     */
    @LayoutRes
    public abstract int getLayoutId();

    /**
     * 绑定
     *
     * @param v view
     */
    public abstract void initView(View v);

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        Window window = dialog.getWindow();
        if (window != null) {
            // 设置宽度为屏宽, 靠近屏幕底部。
            // 一定要设置Background，如果不设置，window属性设置无效
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = getGravity();
            // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
            params.width = getWidth();
            params.height = getHeight();
            window.setAttributes(params);
        }
        dialog.setCanceledOnTouchOutside(getCanceledOnTouchOutside());
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return !getCanceledOnTouchOutside() && keyCode == KeyEvent.KEYCODE_BACK;
            }
        });
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if(onBaseDialogDismiss != null) {
            onBaseDialogDismiss.onDismiss();
        }
    }

    public void setOnDialogDismiss(OnBaseDialogDismissListener onBaseDialogDismiss){
        this.onBaseDialogDismiss = onBaseDialogDismiss;
    }

    public boolean getCanceledOnTouchOutside() {
        return true;
    }

    public int getWidth() {
        return ViewGroup.LayoutParams.MATCH_PARENT;
    }

    public int getHeight() {
        return ViewGroup.LayoutParams.WRAP_CONTENT;
    }

    public interface OnBaseDialogDismissListener{
        void onDismiss();
    }
}
